package lib.gui;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import view.Home;
import view.RegisterDevice;

import lib.Constants;
import lib.Util;
import lib.StringResource;

import lib.classes.VerticalFieldManagerFieldSet;
import model.DB;
import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.PasswordEditField;
import net.rim.device.api.ui.container.HorizontalFieldManager;

public class LoginScreen extends ScreenTemplate implements FieldChangeListener
{
	AutoTextEditField username;
	PasswordEditField password;
	CheckboxField remember;
	ButtonField submit;
	public LoginScreen()
	{
		super("Login", true);
		checkSDCard();
		username = new AutoTextEditField("Username: ","", Integer.MAX_VALUE, USE_ALL_WIDTH);
		username.setPadding(5, 5, 5, 5);
		password = new PasswordEditField("Password: ", "", Integer.MAX_VALUE, USE_ALL_WIDTH);
		password.setPadding(5, 5, 5, 5);
		remember = new CheckboxField("Remember Me", false, Field.FIELD_LEFT);
		remember.setPadding(5, 5, 5, 5);
		submit = new ButtonField(" Login ", Field.FIELD_RIGHT);
		submit.setPadding(5, 5, 5, 5);
		submit.setChangeListener(this);
		VerticalFieldManagerFieldSet pan = new VerticalFieldManagerFieldSet();
		pan.setPadding(5, 5, 5, 5);
		pan.add(username);
		pan.add(password);
		pan.add(remember);
		ButtonField register = new ButtonField(" New User ");
		register.setPadding(5, 5, 5, 5);
		register.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) 
			{
				int response = Dialog.ask(Dialog.D_YES_NO, StringResource.REGISTER_WARNING_MSG);
				switch(response)
				{
					case Dialog.YES:
						switchScreen(new RegisterDevice());
					break;
					case Dialog.NO:
						//Do Nothing
					break;
					default:
						//Do Nothing
					break;
				}				
			}
		});
		add(pan);
		HorizontalFieldManager x = new HorizontalFieldManager(USE_ALL_WIDTH);
		x.add(register);x.add(submit);
		add(x);
	}
	public void fieldChanged(Field field, int context) 
	{
		if(isValidForm())
		{
			if(loginCorrect())
			{
				_db.login(username.getText(), password.getText(), remember.getChecked());
				switchScreen(new Home());
			}else
			{
				Dialog.alert(StringResource.WRONG_EMAIL_PASSWORD);
			}
		}else
		{
			Dialog.alert(StringResource.COULD_NOT_LOGIN_AT_THIS_TIME);
		}
	}
	private boolean loginCorrect() 
	{
		boolean logincorrect = false;
		try
        {
			HttpConnection httpConn = (HttpConnection)Connector.open(Util.Host(DB.serverURL, -1), Connector.READ_WRITE);
			URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
        	encPostData.append("action", "login");
        	encPostData.append("pin", DeviceInfo.getDeviceId()+"");
        	encPostData.append("username", username.getText());
        	encPostData.append("password", password.getText());
        	byte[] postDataBytes = encPostData.getBytes();
        	
        	httpConn.setRequestMethod(HttpConnection.POST);
        	httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        	httpConn.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
        	httpConn.setRequestProperty("Content-Language", "en-US");
        	httpConn.setRequestProperty("Content-Length",new Integer(postDataBytes.length).toString());
        	
            int rc = httpConn.getResponseCode();
            if(rc == HttpConnection.HTTP_OK) 
            {
            	OutputStream os = httpConn.openOutputStream();
                os.write( postDataBytes );
                InputStream is;
                is = httpConn.openInputStream();
                byte[] _data = new byte[100];
                is.read( _data );
                String x = new String(_data);
                System.out.println("Login: " + x);
                if( Util.isNumeric(x.trim()) )
                {
                	int rtnCode = Integer.parseInt(x.trim());
                    switch (rtnCode)
                    {
                    	case Constants.CODE_LOGIN_SUCCESSFUL_SAMEDEVICE:
                    		logincorrect = true;
                    		break;
                    	case Constants.CODE_LOGIN_SUCCESSFUL_DIFFDEVICE:
                    	{
                    		String msg = StringResource.LOGIN_SUCCESS_DIFFDEVICE;
                    		msg += "\r\nWould you like to link this email to this device, doing so will unlink this email address from the previous device";
                    		int response = Dialog.ask(Dialog.D_YES_NO, msg);
                    		if(response == Dialog.YES)
                    		{
                    			if (Util.migratePinToEmail(DeviceInfo.getDeviceId(), username.getText()))
                    				logincorrect = true;
                    		}
                    		else
                    			logincorrect = false;
                    		break;
                    	}
                    	case Constants.CODE_LOGIN_UNSUCCESSFUL_SAMEDEVICE:
                    		Dialog.alert(StringResource.WRONG_EMAIL_PASSWORD);
                    		break;
                    	case Constants.CODE_LOGIN_UNSUCCESSFUL_NODEVICE:
                    	{
                    		String msg = StringResource.LOGIN_UNSUCCESSFUL_NODEVICE;
                    		int response = Dialog.ask(Dialog.D_YES_NO, msg);
                    		if(response == Dialog.YES)
                    		{
                    			if (Util.migratePinToEmail(DeviceInfo.getDeviceId(), username.getText()))
                    				logincorrect = true;
                    		}
                    		else
                    			logincorrect = false;
                    		break;
                    	}
                    	default:
                    		break;
                    	
                    }
                }
            }else
            {
            	System.out.println("RC is not ok: " + rc);
            }
        }catch(Exception e)
        {
        	System.out.println(e.getMessage());
        }
		return logincorrect;
	}
	private boolean isValidForm() 
	{
		return username.getText().trim().length() > 0 && password.getText().trim().length()>0;
	}
}
